"use client";

import { Card, CardContent, CardHeader, CardTitle } from "@/components/ui/card";
import { Tetromino } from "@/lib/tetris";
import { motion } from "framer-motion";

interface TetrisPreviewProps {
  nextPiece: Tetromino;
}

const TetrisPreview = ({ nextPiece }: TetrisPreviewProps) => {
  // 渲染预览网格
  const renderPreview = () => {
    // 创建一个4x4的空网格
    const grid = Array(4).fill(null).map(() => Array(4).fill(null));
    
    // 计算居中偏移
    const offsetY = Math.floor((4 - nextPiece.shape.length) / 2);
    const offsetX = Math.floor((4 - nextPiece.shape[0].length) / 2);
    
    // 将方块放置在网格中央
    for (let y = 0; y < nextPiece.shape.length; y++) {
      for (let x = 0; x < nextPiece.shape[y].length; x++) {
        if (nextPiece.shape[y][x]) {
          grid[y + offsetY][x + offsetX] = nextPiece.type;
        }
      }
    }
    
    return grid;
  };

  const previewGrid = renderPreview();

  return (
    <Card className="bg-card/60 backdrop-blur-md border-primary/30 shadow-md shadow-purple-500/20">
      <CardHeader className="pb-2">
        <CardTitle className="text-sm font-medium bg-gradient-to-r from-blue-400 to-purple-500 bg-clip-text text-transparent">下一个方块</CardTitle>
      </CardHeader>
      <CardContent>
        <div className="tetris-preview w-full aspect-square p-2 rounded-md">
          {previewGrid.map((row, y) =>
            row.map((cell, x) => (
              <motion.div
                key={`preview-${y}-${x}`}
                className={`tetris-cell ${
                  cell ? nextPiece.color : "bg-transparent"
                } border ${cell ? "border-white/30" : "border-indigo-900/30"}`}
                initial={{ opacity: cell ? 0 : 1, scale: cell ? 0.8 : 1 }}
                animate={{ opacity: 1, scale: 1 }}
                transition={{ duration: 0.2 }}
                whileHover={{ scale: cell ? 1.1 : 1, rotate: cell ? 5 : 0 }}
              />
            ))
          )}
        </div>
      </CardContent>
    </Card>
  );
};

export default TetrisPreview;